package rmdb

import (
	"database/sql"
	"errors"

	s "gitee.com/xiaoa7/jsetl/service"
	_ "github.com/ClickHouse/clickhouse-go/v2"
	_ "github.com/go-sql-driver/mysql"
	_ "github.com/lib/pq"
	_ "github.com/mattn/go-sqlite3"
)

type (
	RMDB struct {
		database *sql.DB
	}
)

// 数据库连接工厂
func connectDbFactory(p ...string) (*sql.DB, error) {
	//数据库类型
	switch p[0] {
	case "sqlite":
		return sql.Open("sqlite3", p[1])
	case "msyql", "tidb":
		return sql.Open("mysql", p[1])
	case "clickhouse":
		return sql.Open("clickhouse", p[1])
	case "postgres":
		return sql.Open("postgres", p[1])
	}
	return nil, errors.New("未知的数据库类型")
}

// 连接数据库
func ConnectDB(key string, p ...string) error {
	if _db, err := connectDbFactory(p...); err == nil {
		s.RegisteService(key, &RMDB{_db})
		return nil
	} else {
		return err
	}
}

// 空实现
func (r *RMDB) Connect(key string, p ...string) error {
	return nil
}

// 断开连接
func (r *RMDB) Destory() error {
	if r.database != nil {
		r.database.Close()
	}
	return nil
}
